package net.knightwatch.kwtools;

import java.util.ArrayList;

import net.knightwatch.kwtools.customers.Building;
import net.knightwatch.kwtools.customers.BuildingArrayAdapter;
import net.knightwatch.kwtools.customers.Customer;
import net.knightwatch.kwtools.database.KwToolsDatasource;
import net.knightwatch.kwtools.walkthrough.Potential;
import net.knightwatch.kwtools.walkthrough.PotentialArrayAdapter;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
/*
 * Customer Activity will be used to create a new customer
 * View a customer and their buildings, potentials
 * Plus give the ability to add new potentials and buildings to the customer object
 * New Customer Layout = customer_activity_details.xml
 * View Customer Layout = 
 */
public class CustomerActivity extends Activity {
	private static final String TAG = "CustomerDetailActivity";	
	private KwToolsDatasource datasource = new KwToolsDatasource(this);
	private Customer customer;
	private Boolean readOnly;
	// Edit layout
	private EditText editCustomerName;
	private ListView buildingListView;
	BuildingArrayAdapter buildingArrayAdapter;
	ArrayList<Building> customerBuildings;
	private ListView potentialListView;
	PotentialArrayAdapter potentialArrayAdapter;
	ArrayList<Potential> customerPotentials;
	
	/** Called when the activity is first created. */
	   @Override
	   public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        Log.d(TAG, "Intent Started with Customer ID = " + getIntent().getLongExtra("customerId", 0) + " Read Only = " + getIntent().getBooleanExtra("readOnly", false));
	        // Get information from the intent if the activity is reading a customer or creating
	        readOnly = getIntent().getBooleanExtra("readOnly", true);
	        // Create a new customer object
	        this.customer = new Customer();
	        if (readOnly){
	        	// View the customer, buildings, potentials
	    		setContentView(R.layout.customer_activity_detail);
	    		// Get the customer id from intent
	    		customer.setCustomerId(getIntent().getLongExtra("customerId", -1));	 
	    		try{
	    			datasource.Open();
	    			customer = datasource.getCustomer(customer.getCustomerId());
	    		} catch (Exception e){
	    			e.printStackTrace();
	    		} finally { 
	    			datasource.Close();
	    		}
	        	// TODO Change this to a separate tab
	    		// Get the customer information
	    		createCustomerNameEditText();
	    		// TODO Change this to a separate tab
	    		// Get the customers buildings
	    		createBuildingListView();
	    		// TODO Change this to a separate tab
	    		// Get the list of the potentials
	    		createPotentialListView();
	    		
	        } else {
	        	// Create a new customer
	        	setContentView(R.layout.customer_activity_add_customer);
	        	createCustomerNameEditText();
	        }
	        
	   }
	private void createPotentialListView() {
		customerPotentials = new ArrayList<Potential>();
		potentialListView = (ListView)findViewById(R.id.potentialListView);
		potentialArrayAdapter = new PotentialArrayAdapter(this, R.layout.potential_list_item, customerPotentials);
		potentialListView.setAdapter(potentialArrayAdapter);
		// Item Click Listener for the objects in the list. 
		potentialListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapter, View view,
					int position, long id) {
				// On the click of the potential list item
				Potential potential = (Potential) potentialListView.getItemAtPosition(position);
				Log.d(TAG, "You have selected potential id = " + potential.getId());
				Intent intent = new Intent(view.getContext(), PotentialActivity.class);
				intent.putExtra("readOnly", true);
				intent.putExtra("potentialId", potential.getId());
				startActivity(intent);
			}
		});
	}
	
	private void createBuildingListView() {
		customerBuildings = new ArrayList<Building>();
		buildingListView = (ListView)findViewById(R.id.buildingListView);
		buildingArrayAdapter = new BuildingArrayAdapter(CustomerActivity.this, R.layout.building_list_item, customerBuildings);
		buildingListView.setAdapter(buildingArrayAdapter);
		buildingListView.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> adapter, View view, int position,
					long id) {
				// TODO Launch building activity putting the building id to lookup to edit the details
				Building building = (Building) buildingListView.getItemAtPosition(position);
				Log.d(TAG, "You have selected building id = " + building.getId());
				Intent intent = new Intent(view.getContext(), BuildingActivity.class);
				intent.putExtra("buildingId", building.getId());
				intent.putExtra("customerId", customer.getCustomerId());
				startActivity(intent);
			}
			
		});
	}
	private void createCustomerNameEditText() {
		editCustomerName = (EditText)findViewById(R.id.customerName_etxt);
		editCustomerName.setText(customer.getCustomerName());
		editCustomerName.addTextChangedListener(new TextWatcher(){

			public void afterTextChanged(Editable s) {
				// Update the customers name when the text has changed.
				customer.setCustomerName(s.toString());
			}

			public void beforeTextChanged(CharSequence s, int start,
					int count, int after) {
			
			}

			public void onTextChanged(CharSequence s, int start,
					int before, int count) {
				
			}
			
		});
	}
	private class UpdateBuildingsTask extends AsyncTask<Long, Void, Void>{

		@Override
		protected Void doInBackground(Long... params) {
			// TODO Update the list of the buildings for the customer
			long customerId = params[0];
			try{
				datasource.Open();
				// TODO Query as Async Task
				customerBuildings.clear();
				for (Building b : datasource.getCustomerBuildings(customerId)){
					customerBuildings.add(b);
				}
			} catch (SQLException e){
				Log.e(TAG, "Unable to refresh building list");
				e.printStackTrace();
			} finally {
				datasource.Close();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			buildingArrayAdapter.notifyDataSetChanged();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
		
	}
	private class UpdatePotentialsTask extends AsyncTask<Long, Void, Void>{

		@Override
		protected Void doInBackground(Long... params) {
			// Update the list of potentials
			long customerId = params[0];
			try{
				datasource.Open();
				customerPotentials.clear();
				for(Potential p : datasource.getCustomerPotentials(customerId)){
					customerPotentials.add(p);
				}
			} catch (Exception e){
				e.printStackTrace();
				Log.e(TAG, "Unable to retrieve list of potentials for the customer.");
			} finally { 
				datasource.Close();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Notify the array adapter of the updated data set
			potentialArrayAdapter.notifyDataSetChanged();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
	}
	@Override
	public void onResume(){
		super.onResume();
		//TODO Clean this up
		if (customer.getCustomerId() > 0){
			// Update the building information
			new UpdateBuildingsTask().execute(customer.getCustomerId());
			// Update the potential information
			new UpdatePotentialsTask().execute(customer.getCustomerId());
		}
	}
	@Override
		public boolean onCreateOptionsMenu(Menu menu) {
		   MenuInflater inflater = getMenuInflater();
		   inflater.inflate(R.menu.customer_activity_menu, menu);		   
		   return true;
		}
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			Intent intent = null;
		    switch (item.getItemId()) {
		    case R.id.save:
            	SaveCustomer();
	        	return true;
		    case R.id.addBuilding:
				intent = new Intent(this, BuildingActivity.class);
				intent.putExtra("customerId", customer.getCustomerId());
				startActivity(intent);
				return true;
		    case R.id.addPotential:
				intent = new Intent(this, PotentialActivity.class);
				intent.putExtra("customerId", customer.getCustomerId());
				startActivity(intent);
				return true;
		    default:
		            return super.onOptionsItemSelected(item);
		    }
		}
		private void SaveCustomer() {
			// Save Customer to the database
			// FIXME add listener to the edit text box and set the value of the newly created customer. 
			// FIXME Change this to AsyncTask
			try {
				datasource.Open();
				if(customer.getCustomerId() == 0){
					customer = datasource.createCustomer(customer);
					Log.v(TAG, "Customer was saved to database");
					Toast.makeText(this, "New Customer has been added and saved.", Toast.LENGTH_SHORT).show();
				} else {
					datasource.updateCustomer(customer);
					Log.v(TAG, "Customer was updated to the database");
					Toast.makeText(this, "The Customer has been updated.", Toast.LENGTH_SHORT).show();
				}
			} catch (SQLException e){
				e.printStackTrace();
				Toast.makeText(this, "The Customer was unable to be saved to the database.", Toast.LENGTH_SHORT).show();
				Log.e(TAG, "Unable to save customer to the database");
			} finally {
				datasource.Close();
				this.finish();
			}
		}
}
